package com.hisense.ovcloud.apicontrol.tool.deprecated;

import cn.hutool.json.JSONConfig;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hisense.ovcloud.apicontrol.config.Constants;
import com.hisense.ovcloud.apicontrol.dto.req.ValidateReq;
import org.apache.commons.lang3.StringUtils;

import java.util.*;
import java.util.stream.Collectors;


public class Test {
    public static LinkedHashMap<String, Object> parseParameters(ValidateReq req) throws JsonProcessingException {
        LinkedHashMap<String, Object> resp = new LinkedHashMap<>();
        if (req.getMethod().equalsIgnoreCase(Constants.Method.GET)) {
            if (StringUtils.isNotEmpty(req.getOrderedParams())) {
                if (req.getOrderedParams().contains("&")) {
                    Arrays.asList(req.getOrderedParams().split("&")).forEach(x -> {
                        String[] keyValue = x.split("=");
                        if (keyValue.length == 2) {
                            resp.put(keyValue[0], keyValue[1]);
                        }
                    });
                } else if (req.getOrderedParams().contains("=")) {
                    String[] keyValue = req.getOrderedParams().split("=");
                    if (keyValue.length == 2) {
                        resp.put(keyValue[0], keyValue[1]);
                    }
                }
            }
            return resp;
        } else if (req.getMethod().equalsIgnoreCase(Constants.Method.POST)) {
            if (StringUtils.isNotEmpty(req.getBody())) {
                return transferBodyToTreeMap(req.getBody());
            }
        }
        return resp;
    }

    private static LinkedHashMap<String, Object> transferBodyToTreeMap(String body) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        // 关键配置：保留 null 值
        mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);

        // 反序列化为 LinkedHashMap（保留顺序）
        return mapper.readValue(
                body,
                mapper.getTypeFactory().constructMapType(
                        LinkedHashMap.class, String.class, Object.class
                )
        );
    }

    private static String buildParamString(TreeMap<String, Object> originMap) {
        TreeMap<String, String> sortedMap = new TreeMap<>();
        originMap.forEach((key, value) -> {
            if (value instanceof String && !value.toString().isEmpty()) {
                sortedMap.put(key, value.toString());
            } else if (value instanceof Integer || value instanceof Long) {
                sortedMap.put(key, value.toString());
            } else if (value instanceof List) {
                if (!((List<?>) value).isEmpty()) {
                    sortedMap.put(key, JSONUtil.toJsonStr(value, new JSONConfig().setIgnoreNullValue(false)));
                }
            } else if (value instanceof Map) {
                if (!((Map<?, ?>) value).isEmpty()) {
                    sortedMap.put(key, JSONUtil.toJsonStr(value, new JSONConfig().setIgnoreNullValue(false)));
                }
            } else {
                    if (!value.toString().isEmpty()) {
                        sortedMap.put(key, value.toString());
                }
            }
        });
        return sortedMap.entrySet().stream()
                .map(entry -> entry.getKey() + "=" + entry.getValue())
                .collect(Collectors.joining("&"));
    }

    public static void testJackson() throws JsonProcessingException {
        String jsonString = "{\"z\":3,\"a\":1,\"b\":null,\"c\":{\"e\":null,\"d\":\"hello\"}}";

        // 配置 ObjectMapper
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        // 关键配置：保留 null 值
        mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);

        // 反序列化为 LinkedHashMap（保留顺序）
        LinkedHashMap<String, Object> resultMap = mapper.readValue(
                jsonString,
                mapper.getTypeFactory().constructMapType(
                        LinkedHashMap.class, String.class, Object.class
                )
        );

        // 输出结果（顺序和 null 值均保留）
        System.out.println(resultMap);
        // {z=3, a=1, b=null, c={e=null, d=hello}}

        // 验证嵌套结构
        LinkedHashMap<String, Object> nestedMap = (LinkedHashMap<String, Object>) resultMap.get("c");
        System.out.println("嵌套中的 e 是否存在: " + nestedMap.containsKey("e")); // true
        System.out.println("嵌套中的 e 值: " + nestedMap.get("e")); // null
    }
    public static void main(String[] args) throws Exception {
        testJackson();
//        System.out.println(
//                JSONUtil.toJsonStr(buildParamString(new TreeMap<>(parseParameters(
//                        ValidateReq.builder()
//                                .contentType("application/json")
//                                .method("GET")
//                                .orderedParams("appId=47110563037231&languageId=1&pageNo=1&pageSize=10&phoneCode=24e94e68016ec3bc4b01cb0e358396d8c&queryType=0&randStr=81ba25d5ffe5e39253e75d2cfc749560&sourceId=td001001000066bb4423e7fbbcea63dad2297beffa8c&timeStamp=1740548278207&timezone=Asia/Shanghai&version=8.1")
//                                .build()
//                ))))
//        );
    }
}
